package com.iteye.trafficRecorder;

import java.util.List;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.IBinder;
import android.util.Log;

public class LocationService extends Service implements ResponseListener {
	
	private GPSHelper gpsHelper;
	
	private SensorHelper sensorHelper;
	
	private DatabaseHelper dbHelper;
	
	private boolean stop = false;
	
	private User user;
	
	private Setting setting;
	
	private MyLocation oldLocation;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("LocationService", "onCreate is run");
		setting = new Setting(this);
        dbHelper = new DatabaseHelper(this);
        dbHelper.openDb();
		gpsHelper = new GPSHelper(this);
		sensorHelper = new SensorHelper(this);
		gpsHelper.start();
		sensorHelper.start();
	}
	
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("LocationService", "onStartCommand is run");
		int result = super.onStartCommand(intent, flags, startId);
        user = dbHelper.getUser();
        if (user != null) {
    		sendLocationThread.start();
        }
		return result;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("LocationService", "onDestroy is run");
		stop = true;
		gpsHelper.stop();
		sensorHelper.stop();
		dbHelper.closeDb();
	}
	
	private Thread sendLocationThread = new Thread() {
		public void run() {
			while (!stop) {
				try {
					Thread.sleep(setting.getGpsRecordsecond() * 1000);
				} catch (InterruptedException e) {
					Log.w("Location", e.getMessage());
				}
				
				Location location = gpsHelper.getCurrentLocation();
				if (location != null) {
					MyLocation myLocation = new MyLocation();
					myLocation.setLocationId(UUID.randomUUID().toString());
					myLocation.setPhoneNum(user.getPhoneNumber());
					myLocation.setTime(System.currentTimeMillis());
					myLocation.setProvider(location.getProvider());//来源
					myLocation.setLongitude(location.getLongitude());//经度
					myLocation.setLatitude(location.getLatitude());//纬度
					//海拔
					if (location.hasAltitude()) {
						myLocation.setAltitude(location.getAltitude());
					}
					// 偏离正北方向的角度
		            if (location.hasBearing()) {  
		            	myLocation.setDirection(location.getBearing());
		            } else {
		            	myLocation.setDirection(sensorHelper.getDegree());
		            }
		            //卫星数
					myLocation.setSatelliteCount(gpsHelper.getSatelliteCount());
					//温度
					myLocation.setTemperature(sensorHelper.getTemperature());
					
					if (oldLocation !=null) {
						float[] results = new float[1];
						Location.distanceBetween(oldLocation.getLatitude(), oldLocation.getLongitude(), myLocation.getLatitude(), myLocation.getLongitude(), results);
						float distance = results[0];
						//距离
						myLocation.setDistance(distance);
			            //速度m/s(*3.6=km/h)
			            if (location.hasSpeed()) {
			            	myLocation.setSpeed(location.getSpeed() * 3.6f);
			            } else {
							long time = myLocation.getTime() - oldLocation.getTime();
							if (time > 0) {
								float speed = distance  / time * 3.6f;
								myLocation.setSpeed(speed);
							}
			            }
					}
					Log.d("LocationService", myLocation.toXml());
					oldLocation = myLocation;
					List<NameValuePair> params = WebService.initParams(WebService.dataType_location, myLocation.getLocationId(), myLocation.toXml());
					try {
						HttpClientHelper.asyncPostTextRequestNoHandler(LocationService.this, setting.getWebServiceUrl(), params, LocationService.this, myLocation);
					} catch (Exception e) {
						Log.e("LocationService", "Error in submit regist info!", e);
					}
				}
			}
		}
	};

	public void onResponseSuccess(HttpResponse response, Object result, Object myLocation) {
		Log.d("LocationService", "location send success");
	}

	public void onResponseFailed(HttpResponse response, Throwable error, Object tagObj) {
		Log.d("LocationService", "location send error:" + error);
		if (setting.isStoreLocal()) {
			MyLocation lcoation = (MyLocation)tagObj;
			if (lcoation != null) {
				dbHelper.insertLocation(lcoation);
			}
		}
	}

}
